package com.muyu.system.service.impl;


import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.system.domain.DanmoProductFootprint;
import com.muyu.system.domain.DmShoppingGoods;
import com.muyu.system.domain.DmShoppingStore;
import com.muyu.system.dto.FootDTO;
import com.muyu.system.dto.ShoppingCountDTO;
import com.muyu.system.mapper.DanmoProductFootprintMapper;
import com.muyu.system.mapper.DanmoUserStoreMapper;
import com.muyu.system.mapper.DmShoppingGoodsMapper;
import com.muyu.system.mapper.DmShoppingStoreMapper;
import com.muyu.system.service.IDanmoProductFootprintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 商品足迹Service业务层处理
 * 
 * @author yangle
 * @date 2025-03-12
 */
@Service
public class DanmoProductFootprintServiceImpl implements IDanmoProductFootprintService
{
    @Autowired
    private DanmoProductFootprintMapper danmoProductFootprintMapper;
    private Object todayVisitorCount;


    /**
     * 查询商品足迹
     * 
     * @param id 商品足迹主键
     * @return 商品足迹
     */
    @Override
    public DanmoProductFootprint selectDanmoProductFootprintById(Long id)
    {
        return danmoProductFootprintMapper.selectDanmoProductFootprintById(id);
    }

    /**
     * 查询商品足迹列表
     * 
     * @param danmoProductFootprint 商品足迹
     * @return 商品足迹
     */
    @Override
    public List<DanmoProductFootprint> selectDanmoProductFootprintList(DanmoProductFootprint danmoProductFootprint)
    {

        return danmoProductFootprintMapper.selectDanmoProductFootprintList(danmoProductFootprint);
    }

    /**
     * 新增商品足迹
     *
     * @param danmoProductFootprint 商品足迹
     * @return 结果
     */
    @Override
    public Result<Integer> insertDanmoProductFootprint(DanmoProductFootprint danmoProductFootprint)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoProductFootprint.setUserId(loginUser.getUserid());
        danmoProductFootprint.setCreateTime(DateUtils.getNowDate());
        danmoProductFootprint.setBrowseTime(DateUtils.getNowDate());
        int i = danmoProductFootprintMapper.insertDanmoProductFootprint(danmoProductFootprint);
        return Result.success(i, "新增成功");
    }

    /**
     * 修改商品足迹
     *
     * @param danmoProductFootprint 商品足迹
     * @return 结果
     */
    @Override
    public Result<Integer> updateDanmoProductFootprint(DanmoProductFootprint danmoProductFootprint)
    {
        danmoProductFootprint.setUpdateTime(DateUtils.getNowDate());
        int i = danmoProductFootprintMapper.updateDanmoProductFootprint(danmoProductFootprint);
        return Result.success(i, "修改成功");
    }

    /**
     * 批量删除商品足迹
     *
     * @param ids 需要删除的商品足迹主键
     * @return 结果
     */
    @Override
    public Result<Integer> deleteDanmoProductFootprintByIds(Long[] ids)
    {
        int i = danmoProductFootprintMapper.deleteDanmoProductFootprintByIds(ids);
        return Result.success(i, "删除成功");
    }

    /**
     * 删除商品足迹信息
     *
     * @param id 商品足迹主键
     * @return 结果
     */
    @Override
    public Result<Integer> deleteDanmoProductFootprintById(Long id)
    {
        int i = danmoProductFootprintMapper.deleteDanmoProductFootprintById(id);
        return Result.success(i, "删除成功");
    }

    @Autowired
    private DmShoppingGoodsMapper dmShoppingGoodsMapper;

    @Override
    public List<Map<String, Object>> footprint(DanmoProductFootprint danmoProductFootprint){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoProductFootprint.setUserId(loginUser.getUserid());

        List<DanmoProductFootprint> danmoProductFootprints = danmoProductFootprintMapper.selectIds(danmoProductFootprint);
        Map<String, List<Map<String, Object>>> dateGroupedMap = new LinkedHashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date today = new Date();
        String todayStr = sdf.format(today);

        for (DanmoProductFootprint productFootprint : danmoProductFootprints) {
            String browseDate = sdf.format(productFootprint.getBrowseTime());
            String displayDate = todayStr.equals(browseDate) ? "今天" : browseDate;

            Map<String, Object> footprintMap = new HashMap<>();
            DmShoppingGoods goods = dmShoppingGoodsMapper.selectDmShoppingGoodsById(productFootprint.getProductId());
            if (goods != null) {
                footprintMap.put("productId", goods.getId());
                footprintMap.put("productImage", goods.getGoodsPic());
                footprintMap.put("price", goods.getGoodsPrice());
                // 添加 DanmoProductFootprint 的 id
                footprintMap.put("footprintId", productFootprint.getId());
            } else {
                continue;
            }

            dateGroupedMap.computeIfAbsent(displayDate, k -> new ArrayList<>()).add(footprintMap);
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, Object>>> entry : dateGroupedMap.entrySet()) {
            Map<String, Object> dateGroupedItem = new HashMap<>();
            dateGroupedItem.put("browseDate", entry.getKey());
            dateGroupedItem.put("footprints", entry.getValue());
            resultList.add(dateGroupedItem);
        }

        return resultList;
    }

    @Autowired
    private DmShoppingStoreMapper dmShoppingStoreMapper;

    @Override
    public List<Map<String, Object>> flagship(DanmoProductFootprint danmoProductFootprint) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoProductFootprint.setUserId(loginUser.getUserid());

        List<DanmoProductFootprint> danmoProductFootprints = danmoProductFootprintMapper.selectIds(danmoProductFootprint);
        Map<String, Map<Long, List<Map<String, Object>>>> dateShopGroupedMap = new LinkedHashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("MM - dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date today = new Date();
        String todayStr = sdf.format(today);

        for (DanmoProductFootprint productFootprint : danmoProductFootprints) {
            String browseDate = sdf.format(productFootprint.getBrowseTime());
            String displayDate = todayStr.equals(browseDate) ? "今天" : browseDate;

            Long shopsId = productFootprint.getShopsId();
            DmShoppingStore dmShoppingStore = dmShoppingStoreMapper.selectStore(shopsId);
            if (dmShoppingStore == null) {
                continue;
            }

            List<DmShoppingGoods> goodsList = dmShoppingGoodsMapper.selectStoreGoods(shopsId);
            if (goodsList == null || goodsList.isEmpty()) {
                continue;
            }

            for (DmShoppingGoods goods : goodsList) {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("productId", goods.getId());
                productMap.put("productImage", goods.getGoodsPic());
                productMap.put("price", goods.getGoodsPrice());

                dateShopGroupedMap.computeIfAbsent(displayDate, k -> new LinkedHashMap<>())
                        .computeIfAbsent(shopsId, k -> new ArrayList<>())
                        .add(productMap);
            }
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map.Entry<String, Map<Long, List<Map<String, Object>>>> dateEntry : dateShopGroupedMap.entrySet()) {
            String date = dateEntry.getKey();
            Map<Long, List<Map<String, Object>>> shopMap = dateEntry.getValue();

            List<Map<String, Object>> shopList = new ArrayList<>();
            for (Map.Entry<Long, List<Map<String, Object>>> shopEntry : shopMap.entrySet()) {
                Long shopsId = shopEntry.getKey();
                DmShoppingStore dmShoppingStore = dmShoppingStoreMapper.selectStore(shopsId);

                // 找到对应的 productFootprint 的 id
                Long footprintId = null;
                for (DanmoProductFootprint footprint : danmoProductFootprints) {
                    if (footprint.getShopsId().equals(shopsId)) {
                        footprintId = footprint.getId();
                        break;
                    }
                }

                Map<String, Object> shopInfoMap = new HashMap<>();
                shopInfoMap.put("storeId", dmShoppingStore.getId());
                shopInfoMap.put("name", dmShoppingStore.getName());
                shopInfoMap.put("avatar", dmShoppingStore.getAvatar());
                shopInfoMap.put("pingfen", dmShoppingStore.getAvatar());
                shopInfoMap.put("shuliang", dmShoppingStore.getAvatar());
                shopInfoMap.put("products", shopEntry.getValue());
                // 添加 productFootprint 的 id
                shopInfoMap.put("footprintId", footprintId);

                shopList.add(shopInfoMap);
            }

            Map<String, Object> dateGroupedItem = new HashMap<>();
            dateGroupedItem.put("browseDate", date);
            dateGroupedItem.put("shops", shopList);
            resultList.add(dateGroupedItem);
        }

        return resultList;
    }

    @Autowired
    private DanmoUserStoreMapper danmoUserStoreMapper;
    @Override
    public Result<FootDTO> count(ShoppingCountDTO shoppingCountDTO) {

        FootDTO footDTO = new FootDTO();
        footDTO.setTodayFoots(getTodayVisitorCount());
        footDTO.setYesterdayFoots(getYesterdayVisitorCount());
        footDTO.setTodayFans(getTodayFansCount());
        footDTO.setYesterdayFans(getYesterdayFansCount());
        return Result.success(footDTO);
    }

    private Integer getYesterdayFansCount() {
        ShoppingCountDTO dto = new ShoppingCountDTO();

        // 设置昨日时间范围（例如：2025-06-16 00:00:00 到 2025-06-16 23:59:59）
        LocalDate yesterday = LocalDate.now().minusDays(1);
        dto.setStartTime(yesterday.atStartOfDay());
        dto.setEndTime(yesterday.atTime(23, 59, 59));
        return danmoUserStoreMapper.getTodayFansCount(dto);

    }

    private Integer getTodayFansCount() {

        ShoppingCountDTO dto = new ShoppingCountDTO();

        // 设置今日时间范围（例如：2025-06-17 00:00:00 到 2025-06-17 23:59:59）
        LocalDate today = LocalDate.now();
        dto.setStartTime(today.atStartOfDay());
        dto.setEndTime(today.atTime(23, 59, 59));

        return danmoUserStoreMapper.getTodayFansCount(dto);
    }

    public int getTodayVisitorCount() {
        ShoppingCountDTO dto = new ShoppingCountDTO();

        // 设置今日时间范围（例如：2025-06-17 00:00:00 到 2025-06-17 23:59:59）
        LocalDate today = LocalDate.now();
        dto.setStartTime(today.atStartOfDay());
        dto.setEndTime(today.atTime(23, 59, 59));

        return danmoProductFootprintMapper.selectFootCount(dto);
    }
    // 获取昨日访客数
    public int getYesterdayVisitorCount() {
        ShoppingCountDTO dto = new ShoppingCountDTO();

        // 设置昨日时间范围（例如：2025-06-16 00:00:00 到 2025-06-16 23:59:59）
        LocalDate yesterday = LocalDate.now().minusDays(1);
        dto.setStartTime(yesterday.atStartOfDay()); // 昨日开始时间
        dto.setEndTime(yesterday.atTime(23, 59, 59)); // 昨日结束时间

        return danmoProductFootprintMapper.selectFootCount(dto);
    }
}
